
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017";
const dbase = 'test';
  
function connect(callback){  
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        callback(db.db(dbase))
        db.close();
    });
}
//swhere查询条件,如{"name":'菜鸟教程'} 
function find(dcollection,swhere,callback){  
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db(dbase);
        dbo.collection(dcollection). find(swhere).toArray(function(err, result) { 
            if (err) throw err;
            callback(result);
            db.close();
        });
    });
}
//swhere查询条件,如{"name":'菜鸟教程'} 
//supdate更新数据，如{ "url" : "https://www.123.com" }
function update(dcollection,swhere,supdate){  
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db(dbase);
        var updateStr = {$set: supdate};
        dbo.collection(dcollection).updateOne(swhere, updateStr, function(err, res) {
            if (err) throw err;
            console.log("文档更新成功");
            db.close();
        });
    });
}
//sdata插入数据,如name: "菜鸟教程", url: "www.runoob" 
function insert(dcollection,sdata){  
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db(dbase);        
        dbo.collection(dcollection).insertOne(sdata, function(err, res) {
            if (err) throw err;
            console.log("文档插入成功");
            db.close();
        });
    });
}
function test(){  
    console.log("文档更新成功");
}

module.exports ={connect,find,update,insert,test};